package com.soft.collateral.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.soft.collateral.entity.*;
import com.soft.collateral.mapper.*;
import com.soft.collateral.service.CollateralService;
import com.soft.collateral.vo.PageQueryVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author yzh
 * @desc TODO
 * @date 2025/7/25
 */
@Service
public class CollateralServiceImpl extends ServiceImpl<CollateralMapper, Collateral> implements CollateralService {
    @Autowired
    private CollateralMapper collateralMapper;
    @Autowired
    private CollateralTypeMapper collateralTypeMapper;
    @Autowired
    private CollateralDetailMapper collateralDetailMapper;
    @Autowired
    private CollateralPicMapper collateralPicMapper;
    @Autowired
    private DocumentMapper documentMapper;

    @Override
    public List<Collateral> listAll() {
        List<Collateral> collaterals = collateralMapper.selectList(null);
        collaterals.forEach(this::loadDetails);
        return collaterals;
    }

    @Override
    public Page<Collateral> pageQuery(PageQueryVO pageQueryVO) {
        Page<Collateral> page = new Page<>(pageQueryVO.getCurrentPage(), pageQueryVO.getPageSize());
        LambdaQueryWrapper<Collateral> wrapper = new LambdaQueryWrapper<>();
        if (pageQueryVO.getTypeId() != null) {
            wrapper.eq(Collateral::getTypeId, pageQueryVO.getTypeId());
        }
        if (StringUtils.hasLength(pageQueryVO.getQueryString())) {
            // 修改搜索条件，同时支持按押品ID、名称或创建人搜索
            wrapper.and(q -> q
                    .like(Collateral::getCollateralId, pageQueryVO.getQueryString())
                    .or()
                    .like(Collateral::getCollateralName, pageQueryVO.getQueryString())
                    .or()
                    .like(Collateral::getCreatedBy, pageQueryVO.getQueryString())
            );
        }
        Page<Collateral> collateralPage = collateralMapper.selectPage(page, wrapper);
        collateralPage.getRecords().forEach(this::loadDetails);
        return collateralPage;
    }

    @Override
    @Transactional
    public boolean saveCollateral(Collateral collateral) {
        // 保存基本信息
        boolean saved = collateralMapper.insert(collateral) > 0;
        if (saved && collateral.getCollateralDetail() != null) {
            // 设置关联ID并保存详细信息
            collateral.getCollateralDetail().setCollateralId(collateral.getCollateralId());
            collateralDetailMapper.insert(collateral.getCollateralDetail());
        }
        // 保存图片
        if (saved && collateral.getCollateralPic() != null && !collateral.getCollateralPic().isEmpty()) {
            for (CollateralPic pic : collateral.getCollateralPic()) {
                pic.setCollateralId(collateral.getCollateralId());
                collateralPicMapper.insert(pic);
            }
        }
        // 保存凭证信息
        if (saved && collateral.getDocument() != null) {
            collateral.getDocument().setCollateralId(collateral.getCollateralId());
            documentMapper.insert(collateral.getDocument());
        }
        return saved;
    }

    @Override
    public Collateral getByIdWithDetails(Integer id) {
        Collateral collateral = collateralMapper.selectById(id);
        if (collateral != null) {
            loadDetails(collateral);
        }
        return collateral;
    }

    @Override
    @Transactional
    public boolean updateCollateral(Collateral collateral) {
        // 1. 更新基本信息
        boolean updated = collateralMapper.updateById(collateral) > 0;

        // 2. 更新详情信息
        if (updated && collateral.getCollateralDetail() != null) {
            collateralDetailMapper.updateById(collateral.getCollateralDetail());
        }

        // 3. 更新图片（先删后增）
        if (updated) {
            collateralPicMapper.delete(new LambdaQueryWrapper<CollateralPic>()
                    .eq(CollateralPic::getCollateralId, collateral.getCollateralId()));

            if (collateral.getCollateralPic() != null) {
                collateral.getCollateralPic().forEach(pic -> {
                    pic.setCollateralId(collateral.getCollateralId());
                    collateralPicMapper.insert(pic);
                });
            }
        }
        // 4. 更新凭证信息
        if (updated && collateral.getDocument() != null) {
            documentMapper.updateById(collateral.getDocument());
        }
        return updated;
    }

    @Override
    @Transactional
    public boolean removeByIdWithDetails(Integer id) {
        // 删除凭证信息
        documentMapper.delete(new LambdaQueryWrapper<Document>()
                .eq(Document::getCollateralId, id));
        // 删除图片
        collateralPicMapper.delete(new LambdaQueryWrapper<CollateralPic>()
                .eq(CollateralPic::getCollateralId, id));
        // 删除详细信息
        collateralDetailMapper.delete(new LambdaQueryWrapper<CollateralDetail>()
                .eq(CollateralDetail::getCollateralId, id));
        // 删除基本信息
        return collateralMapper.deleteById(id) > 0;
    }

    @Override
    public List<CollateralType> getAllCollateralTypes() {
        return collateralTypeMapper.selectList(null);
    }

    private void loadDetails(Collateral collateral) {
        // 加载类型信息
        if (collateral.getTypeId() != null) {
            collateral.setCollateralType(collateralTypeMapper.selectById(collateral.getTypeId()));
        }
        // 加载详细信息
        CollateralDetail detail = collateralDetailMapper.selectOne(
                new LambdaQueryWrapper<CollateralDetail>()
                        .eq(CollateralDetail::getCollateralId, collateral.getCollateralId()));
        collateral.setCollateralDetail(detail);
        // 加载图片信息
        List<CollateralPic> pics = collateralPicMapper.selectList(
                new LambdaQueryWrapper<CollateralPic>()
                        .eq(CollateralPic::getCollateralId, collateral.getCollateralId())
                        .orderByAsc(CollateralPic::getId));
        collateral.setCollateralPic(pics);
        // 加载凭证信息
        Document document = documentMapper.selectOne(
                new LambdaQueryWrapper<Document>()
                        .eq(Document::getCollateralId, collateral.getCollateralId()));
        collateral.setDocument(document);
    }
}


